/*
 *	This file is part of Lounge-Cast.
 *
 *  Author:  	Markus Moormann
 *	E-mail:  	mmoorman@uni-osnabrueck.de
 *	Copyright:	University of Osnabrueck (Zentrum Virtuos)
 * 	Website:	www.uni-osnabrueck.de
 *	Date:		16.02.2011
 *
 *	Lounge-Cast is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *	Lounge-Cast is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Lounge-Cast.  If not, see <http://www.gnu.org/licenses/>.
 */
package webservice.functions;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import eu.medsea.mimeutil.MimeUtil;

import webservice.dbConnection.ConnectionHelper;
import webservice.helper.HelperClass;

/**
 * Class for handling uploaded files
 * it's delivering all files that are linked in database
 * 
 * @author Markus Moormann
 *
 */
@Path("/uploadedFiles")
public class GetUploadedFile {
	
	/**
	 * a logger to log errors, debug information, etc.
	 */
	private static Logger LOG = Logger.getLogger(GetUploadedFile.class);
	/**
	 * folder seperator
	 */
	private String sep = File.separator;
	/**
	 * whether decoder for MimeType recognition are set
	 */
	private static boolean decoderSet = false;

	/**
	 * function for getting files for slides
	 * called as http://example.org/webservice/uploadedFiles/slides/{media_id}/{folder}/{filename}
	 * 
	 * @param media_id the media_id of the slide 
	 * @param folder the subfolder (data or assets)
	 * @param filename the filename 
	 * @return a <code>Responde</code> containing the requested file
	 */
	@GET
	@Path("/slides/{media_id}/{folder}/{filename}")
	public Response getSlide(@PathParam("media_id") String media_id,
							 @PathParam("folder") String folder,
							 @PathParam("filename") String filename) {
		File file = new File(HelperClass.getProperty("generalUploadFolder") + sep + 
								HelperClass.getProperty("slideSubFolder") + sep + 
									media_id + sep + folder + sep + filename);
		if(!file.exists()) {
			LOG.error("File doesn't exist:" + file.getPath());
			throw new WebApplicationException(Response.Status.NOT_FOUND);
		}
		if(!GetUploadedFile.decoderSet)
		{
			MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
			MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.ExtensionMimeDetector");
			GetUploadedFile.decoderSet = true;
		}
		
		Collection<?> mimeTypes = MimeUtil.getMimeTypes(file);
		ResponseBuilder builder = Response.status(200);
		builder.type(MimeUtil.getMostSpecificMimeType(mimeTypes).toString());
		builder.header("Content-Length", Long.toString(file.length()));
		builder.header("Content-Disposition","inline; filename=\"" + filename + "\"");
		builder.entity(file);
		return builder.build();
	}
	
	/**
	 * function for common file download, files lying on the server
	 * called as http://example.org/webservice/uploadedFiles/files/{file_id}
	 * 
	 * @param file_id the id of the file
	 * @param disposition the disposition (inline or attachment)
	 * @return a <code>Response</code> containing the requested file
	 */
	@GET
	@Path("/files/{file_id}")
	public Response getUploadedFile(@PathParam("file_id") String file_id, 
									@QueryParam("disposition") @DefaultValue("") String disposition) {
		String selectFileQuery = "";
		//String filename = "";
		String mime_type = "";
		String path = "";
		Long filesize = 0L;
		Connection connection = null;
		Statement statement = null;
		try {
			connection = ConnectionHelper.getConnection();
			statement = connection.createStatement();
			
			int pointIndex = file_id.indexOf('.');
			//remove the extension which is needed for OSMF
			if(pointIndex >= 0)
			{
				file_id = file_id.substring(0, pointIndex);
			}
			
			selectFileQuery = 	"SELECT " +
									"`filename`," +
									"`path`, " +
									"`filesize`," +
									"`mime_type` " 	  +
								"FROM " +
									"`uploaded_files` " +
								"WHERE " +
									"`file_id` = '" + file_id + "'";
			
			ResultSet rs = statement.executeQuery(selectFileQuery);
			if(rs.next()) {
				//filename = rs.getString(1);
				path = rs.getString(2);
				filesize = rs.getLong(3);
				mime_type = rs.getString(4);
			} else {
				LOG.error("Requested file with id:" + file_id + " not found");
				throw new WebApplicationException(Response.Status.NOT_FOUND);
			}
		} catch (SQLException e) {
			LOG.fatal(e);
			throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
		} finally {
			ConnectionHelper.close(connection);
			ConnectionHelper.close(statement);
		}
		
		File file = new File(path);
		ResponseBuilder builder = Response.status(200);
		
		builder.type(mime_type);
		//builder.header("Content-Disposition",(disposition.equals("attachment") ? "attachment ": "inline") + "; filename=\"" + filename + "\"");
		builder.header("Content-Length", Long.toString(filesize));
		builder.entity(file);
		return builder.build();
	}
	
	/**
	 * load an external file over HTTP and deliver it
	 * called as http://example.org/webservice/uploadedFiles/remote/{remote_file_id}
	 * 
	 * @param remote_file_id the id of the remote_file in database
	 * @return <code>Response</code> containing the external file
	 */
	@GET
	@Path("/remote/{remote_file_id}")
	public Response getRemoteFile(@PathParam("remote_file_id") String remote_file_id) {
		ResponseBuilder builder = Response.status(200);
		Connection connection = null;
		Statement statement = null;
		try {
			connection = ConnectionHelper.getConnection();
			statement = connection.createStatement();
			
			String getRemoteURL = 	"SELECT " +
										"remote_url " +
									"FROM " +
										"remote_files " +
									"WHERE " +
										"remote_file_id = '" + remote_file_id + "'";
			
			ResultSet rs = statement.executeQuery(getRemoteURL);
			if(rs.next()) {
				HttpClient client = new HttpClient();
				HttpMethod get = new GetMethod(rs.getString("remote_url"));
				client.executeMethod(get);
				String contentType = get.getResponseHeader("Content-type").getValue();
				String contentLength = get.getResponseHeader("Content-Length").getValue();
				builder = Response.status(200);
				builder.header("Content-Length", contentLength == null ? get.getResponseBody().length : contentLength);
				builder.header("Content-type", contentType == null ? "application/octet-stream" : contentType);
				builder.entity(get.getResponseBodyAsStream());
			} else {
				LOG.error("Requested remote file with id " + remote_file_id + " not found");
				throw new WebApplicationException(Response.Status.NOT_FOUND);
			}
		} catch (HttpException e) {
			LOG.error("HttpException when try loading external file: " + remote_file_id + "\n" + e);
			throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
		} catch (IOException e) {
			LOG.error("IOException when try loading external file: " + remote_file_id + "\n" + e);
			throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
		} catch (SQLException e) {
			LOG.error("SQLException when try loading external file: " + remote_file_id + "\n" + e);
			throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
		} finally
		{
			ConnectionHelper.close(connection);
			ConnectionHelper.close(statement);
		}
		
		return builder.build();
	}
	
	/**
	 * load an external converted SWFs
	 * called as http://example.org/webservice/uploadedFiles/remoteSlide/{remote_file_id}/{folder}/{filename}"
	 * 
	 * @param remote_file_id the corresponding id in database
	 * @param folder the underlying folder ('data'|'assets')
	 * @param filename the filename ('Slide1.swf'|'viewer.xml')
	 * 
	 * @return a <code>Response</code> containing the file
	 */
	@GET
	@Path("/remoteSlide/{remote_file_id}/{folder}/{filename}")
	public Response getRemoteSlide(@PathParam("remote_file_id") String remote_file_id,
								   @PathParam("folder") String folder,
								   @PathParam("filename") String filename) {
		ResponseBuilder builder = Response.status(400);
		Connection connection = null;
		Statement statement = null;
		try {
			connection = ConnectionHelper.getConnection();
			statement = connection.createStatement();
			
			String getRemoteURL = 	"SELECT " +
										"remote_url " +
									"FROM " +
										"remote_files " +
									"WHERE " +
										"remote_file_id = '" + remote_file_id + "'";
			
			ResultSet rs = statement.executeQuery(getRemoteURL);
			if(rs.next()) {
				HttpClient client = new HttpClient();
				HttpMethod get = new GetMethod(rs.getString("remote_url") + "/" + folder + "/" + filename);
				client.executeMethod(get);
				String contentType = get.getResponseHeader("Content-type").getValue();
				builder = Response.status(200);
				builder.header("Content-type", contentType == null ? "application/octet-stream" : contentType);
				builder.entity(get.getResponseBodyAsStream());
			}
			
		} catch (HttpException e) {
			LOG.error("HttpException when try loading external slide: " + remote_file_id + "\n" + e);
			throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
		} catch (IOException e) {
			LOG.error("IOException when try loading external slide: " + remote_file_id + "\n" + e);
			throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
		} catch (SQLException e) {
			LOG.error("SQLException when try loading external slide: " + remote_file_id + "\n" + e);
			throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
		} finally
		{
			ConnectionHelper.close(connection);
			ConnectionHelper.close(statement);
		}
		
		return builder.build();
	}

}
